<template>
  <div class="contentBox setScrollbar">
    <div class="btnBox">
      <el-button type="primary" @click="addRole">新建角色</el-button>
      <!-- <el-form :inline="true" :model="searchObj" class="demo-form-inline">
        <el-form-item label="角色名">
          <el-input v-model="searchObj.name" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button type="primary" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
      <div>
        <el-button type="primary" @click="addRole">新建角色</el-button>
      </div> -->
    </div>

    <el-table v-loading="loading" :data="tableData" border stripe style="width: 100%">
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column prop="name" label="角色名称" width="280" show-overflow-tooltip/>
      <el-table-column prop="description" label="角色描述" show-overflow-tooltip/>
      <el-table-column align="center" prop="isOpen" label="状态" width="180">
        <template slot-scope="scope">{{ scope.row.isOpen==1?'启用':'禁用' }}</template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="400">
        <template slot-scope="scope">
          <el-button
            size="mini"
            class="MR18 bg5584FF"
            type="primary"
            :disabled="scope.row.state==1"
            @click="allotRole(scope.row)"
          >分配权限</el-button>
          <el-button
            size="mini"
            class="MR18 bg5584FF"
            type="primary"
            @click="editRole(scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            class="MR18 bg5584FF"
            type="primary"
            @click="deleteRole(scope.row.roleId)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pageBox">
      <el-pagination
        background
        :current-page.sync="currentPage"
        :page-size="10"
        layout="prev, pager, next, jumper"
        :total="total"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 新增角色 -->
    <el-dialog
      title="新增角色"
      :visible.sync="addDialogVisible"
      width="50%"
      :close-on-click-modal="false"
      @closed="addHandleClose"
    >
      <el-form
        ref="ruleForm"
        v-loading="addLoading"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm paddLr20 textarea200 input40"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model.trim="ruleForm.name" placeholder="请输入" maxlength="20" />
        </el-form-item>

        <el-form-item label="角色状态：">
          <el-radio-group v-model="ruleForm.isOpen">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="ruleForm.description" type="textarea" maxlength="500" />
        </el-form-item>
        <div class="formBtnBox">
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="addDialogVisible = false">取消</el-button>
        </div>
      </el-form>
    </el-dialog>

    <!-- 编辑角色 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editDialogVisible"
      width="50%"
      :close-on-click-modal="false"
      @closed="editHandleClose"
    >
      <el-form
        ref="editRuleForm"
        :model="editRuleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm paddLr20 textarea200 input40"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model.trim="editRuleForm.name" maxlength="200" />
        </el-form-item>

        <el-form-item label="角色状态：" prop="state">
          <el-radio-group v-model="editRuleForm.isOpen">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色描述" prop="desc">
          <el-input v-model="editRuleForm.description" type="textarea" maxlength="500" />
        </el-form-item>
        <div class="formBtnBox">
          <el-button type="primary" @click="editSubmitForm('editRuleForm')">提交</el-button>
          <el-button @click="editDialogVisible = false">取消</el-button>
        </div>
      </el-form>
    </el-dialog>
    <!-- 删除弹窗 -->
    <el-dialog
      title="删除角色"
      :visible.sync="delDialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <p>确认要删除该角色？此操作不可逆</p>
      <div class="formBtnBox">
        <el-button type="primary" @click="sureDelete">确定</el-button>
        <el-button @click="delDialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog
      title="分配权限"
      :visible.sync="allotRoleDialogVisible"
      width="30%"
      :close-on-click-modal="false"
      @closed="allotHandleClose"
    >
      <el-tree
        ref="allotRoleTree"
        :data="treeData"
        show-checkbox
        node-key="id"
        :props="defaultProps"
      />
      <div class="formBtnBox">
        <el-button type="primary" @click="sureAllotRole">确定</el-button>
        <el-button @click="allotRoleDialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { Message } from "element-ui";
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      addDialogVisible: false,
      editDialogVisible: false,
      delDialogVisible: false,
      allotRoleDialogVisible: false,

      loading: false,
      addLoading: false,
      editLoading: false,
      currentPage: 1,
      current: 1,
      total: 0,
      roleId: "",
      delRoleId: "",
      defaultChecked: [],
      searchObj: {
        name: ""
      },
      ruleForm: {
        isOpen: 1
      },
      editRuleForm: {},
      rules: {
        name: [{ required: true, message: "请输入角色名称", trigger: "blur" }]
      },

      tableData: [],
      treeData: [],
      defaultProps: {
        children: "childs",
        label: "name"
      }
    };
  },
  computed: {
    ...mapGetters(["userId"])
  },
  created() {
    this.geTabdata({ current: 1, limit: 10 });
    this.getTreeData();
  },
  methods: {
    geTabdata(searchObj, pageObj) {
      this.loading = true;
      const pms = Object.assign(searchObj, pageObj);
      this.$axios
        .get("/role/list", { params: pms })
        .then(res => {
          this.tableData = res.data.records;
          this.total = res.data.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    getTreeData() {
      this.$axios.get("/menu/selectMenuTreeList").then(res => {
        this.treeData = res.data;
      });
    },
    onSearch() {
      this.geTabdata(this.searchObj, { current: 1, limit: 10 });
    },
    onReset() {
      this.searchObj = {
        name: ""
      };
      this.geTabdata({ current: 1, limit: 10 });
    },
    addRole() {
      this.addDialogVisible = true;
    },
    submitForm(formName) {
      // 表单提交
      this.$refs[formName].validate(valid => {
        if (valid) {
          const queryParams = {
            "sys_role:data[]": {
              "@column": "*",
              "@where": {
                "name@eq": this.ruleForm.name
              }
            }
          };
          this.COM.jsonsqlForSelect(queryParams).then(res => {
            if (res.data.length > 0) {
              Message.warning("角色已存在");
            } else {
              this.addLoading = true;
              this.$axios
                .post("/role/add", this.ruleForm)
                .then(res => {
                  Message.success("创建成功");
                  this.$set(this.ruleForm, "description", "");
                  this.addDialogVisible = false;
                  this.addLoading = false;
                  this.geTabdata({ current: this.current, limit: 10 });
                })
                .catch(() => {
                  this.addLoading = false;
                });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    editRole(row) {
      this.editDialogVisible = true;
      this.editRuleForm = JSON.parse(JSON.stringify(row));
    },
    editSubmitForm(formName) {
      // 编辑表单提交
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log(this.editRuleForm);
          /* 没有修改角色名 查询出来是本条数据； 修改角色名==》 未重名 无数据 重名 有数据 判断id  */
          let queryParams = {
            "sys_role:data[]": {
              "@column": "*",
              "@where": {
                "name@eq": this.editRuleForm.name
              }
            }
          };
          this.COM.jsonsqlForSelect(queryParams).then(res => {
            if (res.data.length > 0) {
              // 有数据 判断返回的数据id
              console.log(res.data);
              if (res.data[0].role_id == this.editRuleForm.roleId) {
                // 未修改角色名
                this.edit();
              } else {
                // 修改角色名并且重名
                Message.warning("角色已存在");
              }
            } else {
              //修改角色名未重名
              this.edit();
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    edit() {
      let status = "";
      if (this.editRuleForm.isOpen == 0) {
        status = "LOCKED";
      } else {
        status = "ENABLE";
      }
      let updateParams = {
        sys_role: {
          name: this.editRuleForm.name,
          description: this.editRuleForm.description,
          is_open: this.editRuleForm.isOpen,
          "@where": {
            "role_id@eq": this.editRuleForm.roleId
          }
        },
        sys_user: {
          status: status,
          "@where": {
            "role_id@eq": this.editRuleForm.roleId
          }
        }
      };
      this.COM.jsonsqlForUpdate(updateParams)
        .then(res => {
          Message.success("编辑成功");
          this.editDialogVisible = false;
          this.geTabdata({ current: this.current, limit: 10 });
          this.editLoading = false;
        })
        .catch(() => {
          this.editLoading = false;
        });
    },
    deleteRole(id) {
      const queryParams = {
        "sys_user:data[]": {
          "@column": "*",
          "@where": {
            "role_id@eq": id,
            "status@notEq": 'DELETED'
          }
        }
      };
      this.COM.jsonsqlForSelect(queryParams).then(res => {
        if (res.data.length > 0) {
          Message.warning("当前角色存在绑定用户，不能删除");
        } else {
          this.delRoleId = id;
          this.delDialogVisible = true;
        }
      });
    },
    sureDelete() {
      this.$axios
        .get("/role/remove", { params: { roleId: this.delRoleId } })
        .then(() => {
          this.geTabdata({ current: this.current, limit: 10 });
          this.delDialogVisible = false;
          Message.success("已删除");
        });
    },
    handleCurrentChange(val) {
      this.geTabdata({ current: val, limit: 10 });
      this.current = val;
    },
    addHandleClose() {
      this.$refs.ruleForm.resetFields();
      if (this.ruleForm.description) {
        this.$set(this.ruleForm, "description", "");
      }
    },
    editHandleClose() {
      this.$refs.editRuleForm.resetFields();
    },
    allotRole(row) {
      this.allotRoleDialogVisible = true;
      this.roleId = row.roleId;
      this.$axios
        .get("/menu/isCheck", { params: { roleId: row.roleId } })
        .then(res => {
          this.$nextTick(() => {
            this.$refs.allotRoleTree.setCheckedKeys(res.data);
          });
        });
    },
    allotHandleClose() {
      this.$refs.allotRoleTree.setCheckedKeys([]);
    },
    sureAllotRole() {
      // const treeKeys = []
      // this.$refs.allotRoleTree.getCheckedNodes(false,true).forEach(item=>{
      //   treeKeys.push(item.id)
      // })
      const treeKeys = this.$refs.allotRoleTree.getCheckedKeys();
      console.log(treeKeys);
      this.$axios
        .post("/role/setAuthority", { roleId: this.roleId, ids: treeKeys })
        .then(() => {
          Message.success("分配成功");
          this.allotRoleDialogVisible = false;
        })
        .catch(() => {
          Message.success("分配失败，请检查网络");
        });
    }
  }
};
</script>
<style lang="scss" scoped>
.setFormMarBtm {
  display: flex;
  justify-content: space-between;
  .el-form-item {
    margin-bottom: 0;
  }
}
</style>
